//
//  UserAccountModel.swift
//  Swift_WeiBo
//
//  Created by dajie on 15/9/1.
//  Copyright (c) 2015年 dajie. All rights reserved.
//

import UIKit
import Alamofire
import SVProgressHUD

class UserAccountModel: NSObject, NSCoding{
    
    /// 用于调用access_token，接口获取授权后的access token。
    var access_token : String
    //// access_token的生命周期，单位是秒数。
    var expires_in : NSTimeInterval
    /// 当前授权用户的UID。
    var uid : String
    /// 转化后的过期时间
    var expires_time : NSDate
    /// 名字
    var name: String?
    /// 头像
    var avatar_large: String?
    
    init(dict : [String : AnyObject])
    {
        access_token = dict["access_token"] as! String
        expires_in = dict["expires_in"] as! NSTimeInterval
        expires_time = NSDate(timeIntervalSinceNow: expires_in)
        uid = dict["uid"] as! String
    }
    
 /// 归档路径
//    private static let AccountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as? String)!.stringByAppendingPathComponent("account.plist")
    
    private static let AccountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last)?.stringByAppendingString("/account.plist")
    
    /// 获取用户的access_Token
    class func getUserAccountRequest(parm : [String : String] , complete : (accout : UserAccountModel? ,error : NSError?)-> ())
    {
        DataEngine.shareEngine().getAccessTokentRequest(parm, complete: { (JSON, error) -> () in
            if (error != nil)
            {
                SVProgressHUD.showInfoWithStatus("授权失败")
                print("授权失败")
                complete(accout : nil, error: error)
                return
            }
            
             UserAccountModel(dict: JSON as! [String : AnyObject]).getUserInfo(complete)
        })
    }
    
    ///  获取用户的基本信息
    private func getUserInfo(complete : (account : UserAccountModel?, error : NSError?)-> ())
    {
        let parms = ["access_token" : access_token, "uid" : "\(uid)"]
       DataEngine.shareEngine().getUserAccountRequest(parms, complete: { (JSON, error) -> () in
        
        if error != nil {
            complete(account: nil, error: error)
            return
        }
        
        if let dict = JSON as? [NSString: NSObject] {
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            //  归档
            NSKeyedArchiver.archiveRootObject(self, toFile: UserAccountModel.AccountPath!)
            complete(account : self, error: nil)
        }
        else {
            let error = NSError(domain: "HMWeiboError", code: -1, userInfo: ["errorInfo": "数据解析错误"])
            complete(account : nil, error: error)
        }
            print(JSON)
       })
    }
    
//  MARK: - 加载用户信息(判断用户登录没有)
    class func loadUserInfo() -> UserAccountModel?
    {
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(UserAccountModel.AccountPath!) as? UserAccountModel
        {
            // 判断是否过期
            if account.expires_time.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
    
//  MARK: - 归档和解档
    required init(coder aDecoder: NSCoder)
    {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in") as NSTimeInterval
        expires_time = aDecoder.decodeObjectForKey("expires_time") as! NSDate
        uid = aDecoder.decodeObjectForKey("uid") as! String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    func encodeWithCoder(aCoder: NSCoder)
    {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_time, forKey: "expires_time")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
}
